<%
  type_collection = field.polymorphic_type_collection
  type_column = field.association.foreign_type.to_s
  selected_type = field.bindings[:object].send(type_column)
  selected = field.bindings[:object].send(field.association.name)
  collection = selected ? [[field.formatted_value, selected.id]] : [[]]
  column_type_dom_id = form.dom_id(field).sub(field.method_name.to_s, type_column)
  current_action = params[:action].in?(['create', 'new']) ? 'create' : 'update'

  default_options = { float_left: false }

  js_data = type_collection.inject({}) do |options, model|
    source_abstract_model = RailsAdmin.config(form.object.class).abstract_model
    options.merge(model.second.downcase.gsub('::', '-') => {
      xhr: true,
      remote_source: index_path(model.second.underscore, source_object_id: form.object.id, source_abstract_model: source_abstract_model.to_param, current_action: current_action, compact: true),
      float_left: false
    })
  end
%>

<div class="row">
  <div class="col-sm-3">
    <% js_data.each do |model, value| %>
      <div data-options="<%= value.to_json %>" id="<%= model %>-js-options"></div>
    <% end %>
    <%= form.select type_column, type_collection, {include_blank: true, selected: selected_type}, class: "form-select", id: column_type_dom_id, data: { polymorphic: true, urls: field.polymorphic_type_urls.to_json }, style: "float: left; margin-right: 10px;" %>
  </div>
  <div class="col-sm-4">
    <%= form.select field.method_name, collection, {include_blank: true, selected: selected.try(:id)}, class: "form-control", data: { filteringselect: true, options: js_data[selected_type.try(:downcase)] || default_options }, placeholder: 'Search' %>
  </div>
</div>
